<?php
class Synce extends Admin_Controller{
	
	public function __construct(){
		parent::__construct();
		$this->load->Model("Msynce");
	}
	
	// public function index(){
	// 	$this->breadcrumb->append_crumb('Home',admincp_url());
	// 	$this->breadcrumb->append_crumb('Synce',base_url().'admincp/synce');
	// 	$data['template']="synce/index";
	// 	$data['title_page']='<i class="icon20 i-network"></i> Synce Manager';
	// 	$this->load->view("admincp/template",$data);
	// }

	public function index(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_synce'),base_url().'admincp/synce');
		if($this->input->is_ajax_request()){
            $output = $this->Msynce->listSynce();
            $this->output->set_output(json_encode($output));
        }else{
			$data['template']="synce/index";
			$data['title_page']='<i class="icon20 i-network"></i> '.trans('title_synce');
			$this->load->view("admincp/template",$data);
        }
	}

	public function add(){
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_synce'),base_url().'admincp/synce');
		$this->breadcrumb->append_crumb(trans('breadcrumb_synce_add'),base_url().'admincp/synce/add');
		$data['template']="synce/add";
		$data['title_page']='<i class="icon20 i-plus-circle-2"></i> '.trans('title_synce_add');
		if($this->input->server('REQUEST_METHOD') == "POST"){
			$data_insert = array(
				'synce_name' => $this->input->post('synce_name'),
				'synce_action' => $this->input->post('synce_action'),
				'date_add' => date('Y-m-d',time()), 
			);
			$this->Msynce->insert($data_insert);
			$this->session->set_flashdata(array("success"=>trans('message_create_successfully')));
			redirect(base_url()."admincp/synce");
		}
		$this->load->view("admincp/template",$data);
	}

	public function edit(){
		$id = $this->uri->segment(5);
		$this->breadcrumb->append_crumb(trans('breadcrumb_home'),admincp_url());
		$this->breadcrumb->append_crumb(trans('breadcrumb_synce'),base_url().'admincp/synce');
		$this->breadcrumb->append_crumb(trans('breadcrumb_synce_edit'),base_url().'admincp/synce/edit/id/'.$id);
		$data['template']="synce/edit";
		$data['title_page']='<i class="icon20 i-pen-2"></i> '.trans('title_synce_edit');
		$data['info'] = $this->Msynce->get_data($id);
		if($this->input->server('REQUEST_METHOD') == "POST"){
			$data_update = array(
				'synce_name' => $this->input->post('synce_name'),
				'synce_action' => $this->input->post('synce_action'),
				'date_edit' => date('Y-m-d',time()), 
			);
			$this->Msynce->update($data_update,$id);
			$this->session->set_flashdata(array("success"=>trans('message_edit_successfully')));
			redirect(base_url()."admincp/synce");		
		}
		$this->load->view("admincp/template",$data);
	}

	public function delete(){
		$id = $this->uri->segment(5);
		$this->Msynce->delete($id);
		$this->session->set_flashdata(array("success"=>trans('message_delete_successfully')));
		redirect(base_url()."admincp/synce");
	}

	// Weather //
	public function weather(){
		$data['template']="synce/weather";
		$this->load->view("admincp/template",$data);
	}

	public function process_weather(){
		if($this->input->is_ajax_request()){
			$from = microtime(true);

			$path = base_url().'assets/api/data/dataWeather.txt';
			$file = file($path);
			$dataCheck = $file[1];
			$arrDataCheck = explode("\t",$dataCheck);
			$dateCheck = strtotime($arrDataCheck[0]);
			$dateInsertLast = strtotime($this->session->userdata['ses_weather']);
			if($dateCheck > $dateInsertLast){
				$this->db->query('DELETE FROM tpt_weather WHERE date >= "'.$arrDataCheck[0].'"');
				$dataInsert = array();
				$header = $file[0];
				$arrHeader = explode("\t",$header);
				unset($file[0]);
				foreach($file as $item){
					$dataItem = array();
					$arrItem = explode("\t",$item);
					foreach($arrItem as $key => $value){
						$dataItem[trim($arrHeader[$key])] = trim($value);
					}
					$dataInsert[] = $dataItem;
				}
				$this->db->insert_batch('tpt_weather', $dataInsert);
				$data_ses["ses_weather"] = $arrDataCheck[0];
				$this->session->set_userdata($data_ses);
			}
			$path = base_url().'assets/api/data/dataWeatherCurrent.txt';
			$file = file($path);
			$dataCurrent = explode("\t",$file[1]);
			if(count($dataCurrent) != 0){
				$dataUpdate = array(
					'tempCurrent' => $dataCurrent[1],
					'weatherCodeCurrent' => $dataCurrent[2],
					'weatherDescCurrent' => $dataCurrent[3]
				);
				$this->db->where('date',$dataCurrent[0]);
				$this->db->update('tpt_weather',$dataUpdate);
				$icon = '';
				switch ($dataUpdate['weatherCodeCurrent']) {
				    case 113:
				        $icon = "i-sun-2 orange";
				        break;
				    case 116:
				        $icon = "i-cloud";
				        break;
				    case 119:
				        $icon = "i-cloud-2 blue";
					case 143:
				        $icon = "i-brightness-low";
				        break;
				}
				$dataIcon = array('icon' => $icon);
				$dataFinal = array_merge($dataUpdate, $dataIcon);
				$this->pusher->trigger('weather', 'update_weather', $dataFinal);
			}
			$total = microtime(true) - $from;
            $result['html'] = '<div style="width:100%;">
									<span style="float:left"><strong><i class="icon24 i-checkmark-circle"></i> Sync Successful:</strong></span>
									<span class="badge" style="float:right; padding:5px">'.round($total,2).'s</span>
							   </div>';
            echo json_encode($result);
		}
	}

	// Analytics //
	public function analytics(){
		$data['template']="synce/analytics";
		$this->load->view("admincp/template",$data);
	}

	public function process_analytics(){
		if($this->input->is_ajax_request()){
			$from = microtime(true);

			$path = base_url().'assets/api/data/dataAnalytics.txt';
			$file = file($path);
			$dataInsert = array();
			$header = $file[0];
			$arrHeader = explode("\t",$header);
			unset($file[0]);
		  	foreach($file as $item){
				$dataItem = array();
				$arrItem = explode("\t",$item);
				foreach($arrItem as $key => $value){
					$dataItem[trim($arrHeader[$key])] = trim($value);
				}
				$dataInsert[] = $dataItem;
			}	
			$this->db->insert_batch('tpt_analytics', $dataInsert);

			$total = microtime(true) - $from;
            $result['html'] = '<div style="width:100%;">
									<span style="float:left"><strong><i class="icon24 i-checkmark-circle"></i> Sync Successful:</strong></span>
									<span class="badge" style="float:right; padding:5px">'.round($total,2).'s</span>
							   </div>';
            echo json_encode($result);
		}
	}

}